<?
/* connect to mysql db */
require_once './includes/db_connection.php';
echo("db connected<br>");

$user = $_POST['user'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];

$sql_getlogin = "SELECT userid FROM user WHERE username=?";
$sql_putuser = "INSERT INTO user(username, password, lastlog_dt, lastlog_ip) VALUES (?,?,NOW(),?)";


/**
 * Add user into database
 *
 * @param String $user User name
 * @param String $password User password
 *
 * @return int User id
 *
 */
function putuser($user, $password) {
	global $db, $sql_putuser;

	try {
		$psput = $db->prepare($sql_putuser);
		$psput->execute(array($user, md5($password), $_SERVER['REMOTE_ADDR']));
		echo("user added<br>");
		return $db->lastInsertId();
	} catch(Exception $e) {
		die("Chyba SQL [add user]");
	}
}

/* password verification */
if($pass != $pass2) {
	header("Location: http://".$_SERVER["HTTP_HOST"]."/?err=4");
	exit();
}
echo("password verification ok<br>");

/* password have to be longer than 4 characters */
if(strlen($pass) < 5) {
	header("Location: http://".$_SERVER["HTTP_HOST"]."/?err=7");
	exit();
}
echo("password lenght ok<br>");

/* check empty user name field */
if($user == "") {
	header("Location: http://".$_SERVER["HTTP_HOST"]."/?err=6");
	exit();
}
echo("user name not empty<br>");

/* check user name on accepted characters */
if(!preg_match('/^[A-Za-z][A-Za-z0-9]{2,63}$/', $user)) {
	header("Location: http://".$_SERVER["HTTP_HOST"]."/?err=8");
	exit();
}
echo("user name contains accepted characters<br>");


/* get user names from db for duplicity check */
try {
	$pslogin = $db->prepare($sql_getlogin);
	$pslogin->execute(array($user));
	$row = $pslogin->fetch(PDO::FETCH_ASSOC);
	if(!empty($row)) {
		header("Location: http://".$_SERVER["HTTP_HOST"]."/?err=3");
		exit();
	}
	echo("duplicity test ok<br>");

} catch (Exception  $e) {
	die("Chyba SQL [register]");
}

/* put user into db */
$userid = putuser($user, $pass);


/* go to user page */
session_start();
header("Cache-control: private");
$_SESSION["user_isLogged"] = 1;
$_SESSION["user_name"] = $user;
$_SESSION["user_id"] = $userid;
header("Location: ./user.php");
exit();
?>
